package my.suveng.suxinnetty.wsserver;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * create at 2018/10/21
 * author: suveng
 * email: suveng@163.com
 **/
public class CustomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup clients=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        System.out.println("接受到的数据"+text);

        for (Channel channel : clients){
            channel.writeAndFlush(new TextWebSocketFrame("服务器时间"+ LocalDateTime.now()+"消息为："+text));
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        clients.remove(ctx.channel());
        System.out.println( "ctx.channel().id().asLongText()="+ctx.channel().id().asLongText());
        System.out.println("ctx.channel().id().asShortText()="+ctx.channel().id().asShortText());
    }

}
